package com.yangrong.userservice.controller;

import java.util.Arrays;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import com.yangrong.common.constant.UserServiceConstant;
import com.yangrong.common.exception.ErrorCodeEnum;
import com.yangrong.userservice.entity.TbUserEntity;
import com.yangrong.userservice.entity.LoginRequestBean;
import com.yangrong.userservice.feign.ThirdServiceFeignService;
import com.yangrong.userservice.service.TbUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.yangrong.common.utils.PageUtils;
import com.yangrong.common.utils.R;


/**
 * 用户表
 *
 * @author yangrong
 * @email 455833224@qq.com
 * @date 2020-09-04 11:09:13
 */
@RestController
@RequestMapping("user")
public class TbUserController {
    @Autowired
    private TbUserService tbUserService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ThirdServiceFeignService thirdServiceFeignService;

    @PostMapping("/login")
    public R list(@RequestBody LoginRequestBean request) {
        R r = tbUserService.checkLogin(request);

        return R.ok().put("data", r);
    }

    @RequestMapping("/updateUserInfo")
    public R updateUserInfo(@RequestParam Map<String, Object> params) {
        tbUserService.updateUserInfo(params);

        return R.ok();
    }

    @RequestMapping("/sendSmsCode")
    public R sendSmsCode(@RequestParam Map<String, Object> params) {
        String phone = (String) params.get("phone");
        String codeType = (String) params.get("codeType");
        final String SMS_CODE_CACHE_PREFIX;

        if (phone == null || "".equals(phone)) {
            return R.error(ErrorCodeEnum.LOGIN_FAILED_ERROR_PHONE_ISNULL.getCode(), ErrorCodeEnum.LOGIN_FAILED_ERROR_PHONE_ISNULL.getMsg());
        }

        if ("register".equals(codeType)) {
            SMS_CODE_CACHE_PREFIX = UserServiceConstant.SMS_REGISTER_CODE_CACHE_PREFIX;
        } else if ("login".equals(codeType)) {
            if (tbUserService.findUserPhone(phone)) {
                SMS_CODE_CACHE_PREFIX = UserServiceConstant.SMS_LOGIN_CODE_CACHE_PREFIX;
            } else {
                return R.error(ErrorCodeEnum.LOGIN_FAILED_ERROR_PHONE_NOTHAVE.getCode(), ErrorCodeEnum.LOGIN_FAILED_ERROR_PHONE_NOTHAVE.getMsg());
            }
        } else {
            return R.error(ErrorCodeEnum.SMS_CODE_TYPE_EXCEPTION.getCode(), ErrorCodeEnum.SMS_CODE_TYPE_EXCEPTION.getMsg());
        }
        // TODO 接口防刷

        String redisCode = stringRedisTemplate.opsForValue().get(SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                // 60秒内不能再次发送
                return R.error(ErrorCodeEnum.SMS_CODE_EXCEPTION.getCode(), ErrorCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        String code = UUID.randomUUID().toString().substring(0, 5) + "_" + System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(SMS_CODE_CACHE_PREFIX + phone, code, 1, TimeUnit.MINUTES);

        thirdServiceFeignService.getSmsCode(phone, code.split("_")[0]);

        return R.ok();
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = tbUserService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        TbUserEntity tbUser = tbUserService.getById(id);

        return R.ok().put("tbUser", tbUser);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody TbUserEntity tbUser) {
        tbUserService.save(tbUser);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody TbUserEntity tbUser) {
        tbUserService.updateById(tbUser);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        tbUserService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
